/**
 * 用户信息管理模块
 * 统一处理用户信息获取、更新和登录成功后的处理逻辑
 * 集成Pinia store功能，提供统一的用户管理接口
 */

import { setToken, setUserInfo, getUserInfo, removeToken, removeUserInfo } from './storage.js'
import { USER_ROLES } from './constants.js'
import { useUserStore } from '@/stores/user'

/**
 * 获取Pinia用户store实例
 * @returns {object} Pinia store实例
 */
export const getUserStore = () => {
  return useUserStore()
}

/**
 * 初始化用户store状态
 * 从多个存储源恢复用户信息
 */
export const initializeUserStore = () => {
  const userStore = getUserStore()
  
  // 如果store已经有数据，不需要重新初始化
  if (userStore.userId && userStore.token) {
    return userStore
  }
  
  // 从多个来源恢复用户信息
  const userId = uni.getStorageSync('userId')
  const token = uni.getStorageSync('token')
  const userName = uni.getStorageSync('userName')
  
  if (userId && token) {
    userStore.setUserInfo({
      userId: userId,
      userName: userName || '',
      token: token,
      avatar: '',
      role: '',
      points: 0,
      level: 1
    })
  }
  
  return userStore
}

/**
 * 获取当前用户ID
 * @param {boolean} requireLogin - 是否需要登录验证，默认false
 * @returns {string|null} 用户ID或null
 */
export const getCurrentUserId = (requireLogin = false) => {
  const userInfo = getCurrentUserInfo()
  if (userInfo && userInfo.userId) {
    return userInfo.userId
  }
  
  if (requireLogin) {
    uni.showToast({
      title: '请先登录',
      icon: 'none',
      duration: 1500
    })
    setTimeout(() => {
      uni.reLaunch({ url: '/pages/login/login' })
    }, 1500)
  }
  
  return null
}

/**
 * 获取当前用户昵称
 * @returns {string} 用户昵称或默认值
 */
export const getCurrentUserNickname = () => {
  const userInfo = getCurrentUserInfo()
  return userInfo?.nickname || '匿名用户'
}

/**
 * 获取当前用户头像
 * @returns {string} 用户头像URL或默认头像
 */
export const getCurrentUserAvatar = () => {
  const userInfo = getCurrentUserInfo()
  return userInfo?.avatar || '/static/images/default-avatar.png'
}

/**
 * 获取当前用户信息（统一接口）
 * @returns {object} 用户信息对象
 */
export const getCurrentUserInfo = () => {
  try {
    // 1. 优先从Pinia store获取
    const userStore = getUserStore()
    if (userStore.userId && userStore.userName) {
      return {
        id: userStore.userId,
        userId: userStore.userId,
        username: userStore.userName,
        userName: userStore.userName,
        nickname: userStore.userName,
        avatar: userStore.avatar,
        email: userStore.email,
        role: userStore.role,
        points: userStore.points,
        level: userStore.level,
        token: userStore.token
      }
    }
    
    // 2. 从userState获取
    const userStateStr = uni.getStorageSync('userState')
    if (userStateStr) {
      try {
        const userState = JSON.parse(userStateStr)
        if (userState.userId && userState.token) {
          return {
            id: userState.userId,
            userId: userState.userId,
            username: userState.userName,
            userName: userState.userName,
            nickname: userState.userName,
            avatar: userState.avatar,
            email: userState.email,
            role: userState.role,
            points: userState.points,
            level: userState.level,
            token: userState.token
          }
        }
      } catch (parseError) {
        console.error('解析 userState 失败:', parseError)
      }
    }
    
    // 3. 从localStorage获取
    const userId = uni.getStorageSync('userId')
    const token = uni.getStorageSync('token')
    const userName = uni.getStorageSync('userName')
    
    if (userId && token) {
      const userInfo = getUserInfo()
      return {
        id: parseInt(userId),
        userId: parseInt(userId),
        username: userName || userInfo?.username,
        userName: userName || userInfo?.username,
        nickname: userName || userInfo?.nickname,
        avatar: userInfo?.avatar,
        email: userInfo?.email,
        role: userInfo?.role,
        points: userInfo?.points,
        level: userInfo?.level,
        token: token
      }
    }
    
    return null
  } catch (error) {
    console.error('获取当前用户信息失败:', error)
    return null
  }
}





/**
 * 处理登录成功
 * @param {object} response - 登录响应数据
 * @param {object|boolean} loginFormOrRemember - 登录表单数据或是否记住登录
 * @param {string} redirectUrl - 登录后跳转的页面（可选）
 */
export const handleLoginSuccess = (response, loginFormOrRemember = true, redirectUrl = '/pages/home/home') => {
  // 检查响应格式 - 支持两种格式
  const responseData = response.data || response
  const token = responseData.token
  const user = responseData.user
  
  if (!responseData || !token) {
    console.error('登录响应格式错误:', response)
    return false
  }
  
  try {
    // 存储token
    const remember = typeof loginFormOrRemember === 'boolean' ? loginFormOrRemember : true
    setToken(token, remember)
    
    // 存储用户信息
    if (user) {
      const userInfo = {
        id: user.id || user.ID,
        userId: user.id || user.ID, // 添加userId字段以兼容Pinia store
        username: user.username || user.name,
        userName: user.username || user.name, // 添加userName字段以兼容Pinia store
        nickname: user.nickname || user.name,
        avatar: user.avatar,
        email: user.email,
        phone: user.phone,
        role: user.role || USER_ROLES.USER,
        permissions: user.permissions || [],
        createdAt: user.created_at || user.CreatedAt,
        updatedAt: user.updated_at || user.UpdatedAt
      }
      
      // 1. 存储到auth模块
      setUserInfo(userInfo)
      
      // 2. 更新Pinia store
      const userStore = getUserStore()
      userStore.setUserInfo({
        userId: userInfo.userId,
        userName: userInfo.userName,
        avatar: userInfo.avatar || '',
        token: token,
        role: userInfo.role,
        points: userInfo.points || 0,
        level: userInfo.level || 1
      })
      
      // 3. 存储到localStorage
      uni.setStorageSync('userId', userInfo.userId)
      uni.setStorageSync('userName', userInfo.userName)
      uni.setStorageSync('token', token)
      
      console.log('登录成功，用户信息已保存:', userInfo)
    }
    
    // 存储用户ID到localStorage
    const userId = responseData.user_id || responseData.userId || (user ? user.id || user.ID : null)
    if (userId) {
      uni.setStorageSync('userId', userId)
    }
    
    // 触发登录成功事件
    uni.$emit('user:login:success', responseData)
    
    // 如果提供了redirectUrl，则进行页面跳转
    if (redirectUrl && typeof loginFormOrRemember !== 'boolean') {
      // 显示成功提示
      uni.showToast({
        title: '登录成功',
        icon: 'success'
      })
      
      // 延迟跳转
      setTimeout(() => {
        uni.switchTab({
          url: redirectUrl
        })
      }, 1500)
    }
    
    return true
  } catch (error) {
    console.error('处理登录成功失败:', error)
    return false
  }
}

/**
 * 处理登录失败
 * @param {object} error - 错误信息
 */
export const handleLoginFailed = (error) => {
  console.error('登录失败:', error)
  
  // 清除可能存在的旧数据
  removeToken()
  removeUserInfo()
  
  // 触发登录失败事件
  uni.$emit('user:login:failed', error)
}

/**
 * 处理登出
 * @param {boolean} redirect - 是否跳转到登录页
 */
export const handleLogout = (redirect = true) => {
  try {
    // 1. 清除auth模块数据
    removeToken()
    removeUserInfo()
    
    // 2. 清除Pinia store
    const userStore = getUserStore()
    userStore.logout()
    
    // 3. 清除localStorage
    uni.removeStorageSync('userId')
    uni.removeStorageSync('userName')
    uni.removeStorageSync('token')
    uni.removeStorageSync('userState')
    
    // 触发登出事件
    uni.$emit('user:logout')
    
    if (redirect) {
      uni.navigateTo({
        url: '/pages/login/login'
      })
    }
  } catch (error) {
    console.error('处理登出失败:', error)
  }
}

/**
 * 更新用户信息
 * @param {object} updates - 要更新的用户信息
 */
export const updateUserInfo = (updates) => {
  try {
    const currentInfo = getUserInfo()
    if (!currentInfo) {
      console.warn('用户未登录，无法更新信息')
      return false
    }
    
    const updatedInfo = {
      ...currentInfo,
      ...updates,
      updatedAt: new Date().toISOString()
    }
    
    setUserInfo(updatedInfo)
    
    // 触发用户信息更新事件
    uni.$emit('user:info:updated', updatedInfo)
    
    return true
  } catch (error) {
    console.error('更新用户信息失败:', error)
    return false
  }
}

/**
 * 检查是否为当前用户
 * @param {string} userId - 要检查的用户ID
 * @returns {boolean} 是否为当前用户
 */
export const isCurrentUser = (userId) => {
  if (!userId) return false
  const currentUserId = getCurrentUserId()
  return currentUserId === userId
}

/**
 * 获取用户显示名称
 * @returns {string} 用户显示名称
 */
export const getUserDisplayName = () => {
  const userStore = getUserStore()
  return userStore.userName || '匿名用户'
}

/**
 * 获取用户基础信息（用于展示）
 * @returns {object} 用户基础信息
 */
export const getUserBasicInfo = () => {
  const userStore = getUserStore()
  return {
    userId: userStore.userId,
    userName: userStore.userName,
    avatar: userStore.avatar,
    role: userStore.role,
    points: userStore.points,
    level: userStore.level,
    isLogin: userStore.isLogin
  }
}

/**
 * 设置统一用户信息（兼容旧API）
 * @param {object} userInfo - 用户信息对象
 */
export const setUnifiedUserInfo = (userInfo) => {
  try {
    // 1. 存储到auth模块
    setUserInfo(userInfo)
    
    // 2. 更新Pinia store
    const userStore = getUserStore()
    userStore.setUserInfo({
      userId: userInfo.userId || userInfo.id,
      userName: userInfo.userName || userInfo.username,
      avatar: userInfo.avatar || '',
      token: userInfo.token || '',
      role: userInfo.role || '',
      points: userInfo.points || 0,
      level: userInfo.level || 1
    })
    
    // 3. 存储到localStorage
    if (userInfo.userId || userInfo.id) {
      uni.setStorageSync('userId', userInfo.userId || userInfo.id)
    }
    if (userInfo.userName || userInfo.username) {
      uni.setStorageSync('userName', userInfo.userName || userInfo.username)
    }
    if (userInfo.token) {
      uni.setStorageSync('token', userInfo.token)
    }
    
    console.log('统一设置用户信息成功:', userInfo)
    return true
  } catch (error) {
    console.error('设置用户信息失败:', error)
    return false
  }
}

/**
 * 清除登录信息（兼容旧API）
 */
export const clearLoginInfo = () => {
  try {
    // 清除Pinia store
    const userStore = getUserStore()
    userStore.clearUserInfo()
    
    // 清除localStorage - 清除所有可能的键名
    uni.removeStorageSync('userId')
    uni.removeStorageSync('token')
    uni.removeStorageSync('userState')
    uni.removeStorageSync('userName')
    uni.removeStorageSync('user_info')
    uni.removeStorageSync('login_time')
    uni.removeStorageSync('last_user_id')
    
    // 清除新格式存储
    removeToken()
    removeUserInfo()
    
    console.log('登录信息清除完成')
    return true
  } catch (error) {
    console.error('清除登录信息失败:', error)
    return false
  }
}

/**
 * 处理登录错误（兼容旧API）
 * @param {object} error - 错误信息
 * @param {string} action - 操作名称
 */
export const handleLoginError = (error, action = '登录') => {
  console.error(`${action}失败:`, error)
  
  // 清除可能存在的旧数据
  clearLoginInfo()
  
  // 显示错误提示
  uni.showToast({
    title: `${action}失败，请重试`,
    icon: 'none',
    duration: 2000
  })
  
  // 触发登录失败事件
  uni.$emit('user:login:failed', error)
}

/**
 * 更新用户积分
 * @param {number} newPoints - 新的积分值
 */
export const updateUserPoints = (newPoints) => {
  try {
    // 1. 更新Pinia store
    const userStore = getUserStore()
    userStore.updatePoints(newPoints)
    
    // 2. 更新auth模块的用户信息
    const currentUserInfo = getUserInfo()
    if (currentUserInfo) {
      currentUserInfo.points = newPoints
      setUserInfo(currentUserInfo)
    }
    
    console.log('更新用户积分成功:', newPoints)
    return true
  } catch (error) {
    console.error('更新用户积分失败:', error)
    return false
  }
}

/**
 * 获取用户积分
 * @returns {number} 用户积分
 */
export const getUserPoints = () => {
  const userStore = getUserStore()
  return userStore.points || 0
}

/**
 * 获取用户等级
 * @returns {number} 用户等级
 */
export const getUserLevel = () => {
  const userStore = getUserStore()
  return userStore.level || 1
}

/**
 * 检查用户是否已登录
 * @returns {boolean} 是否已登录
 */
export const isUserLoggedIn = () => {
  const userStore = getUserStore()
  return userStore.isLogin || false
}